const express = require('express')
const router = express.Router()
const fs = require('fs')
const path = require('path')
const { mySend, Vtoken, checkParams, formatDate } = require('../utils/index')
const { to } = require('await-to-js')
const public = path.join(__dirname, '../public')
const File = require('../db/model/FileModel')
// const multiparty = require('multiparty');

const multiparty = require('connect-multiparty');
const multipartyMiddleware = multiparty();

//upload delete update list adminList

router.post('/upload', multipartyMiddleware, async (req, res) => {
    const { token } = req.body
    const user = await Vtoken(token)
    if (!user) {
      return mySend(res, 314, 'token不存在或已过期')
    }
    let files = req.files.files
    if(!files) return mySend(res, 1, '请选择文件')
    if(!files.length) files = [files]
    let myPath = mkdirPath(path.join('public/upload/'  + user.username + '/' + formatDate(new Date, 'yyyyMMdd')))
    let body = []
    files.forEach((file) => {
        let readStream=fs.createReadStream(file.path)
        let writeStream=fs.createWriteStream(myPath + '/' + file.originalFilename)
        readStream.pipe(writeStream);
        readStream.on('end',() => {
         fs.unlinkSync(file.path)
        })
        body.push(path.join('/public/upload/'  + user.username + '/' + formatDate(new Date, 'yyyyMMdd') + '/' + file.originalFilename))
    })
    mySend(res, 0, '成功', body)
})

router.post('/add', async (req, res) => {
    const {fileList, token} = req.body
    const checked = checkParams({ fileList, token })
    if (checked) return mySend(res, 1, checked)
    const user = await Vtoken(token)
    if (!user) return mySend(res, 314, 'token不存在或已过期')
    let list = []
    fileList.forEach(file => {
        list.push({
            userId: user._id,
            username: user.username,
            path: file
        })
    })
    let [err, result] = await to(File.insertMany(list))
    if(err) return mySend(res, 1, '添加失败', err)
    return mySend(res, 0, '添加成功', result)

})

router.post('/delete', async (req, res) => {
    const { filename, token } = req.body
    const checked = checkParams({ filename, token })
    if (checked) return mySend(res, 1, checked)
    const user = await Vtoken(token)
    if (!user) return mySend(res, 314, 'token不存在或已过期')
    let myPath = public + '/' + user.username;
    const exists = fs.existsSync(myPath + '/' + filename)
    if (!exists) return mySend(res, 1, '文件不存在')

    fs.unlinkSync(myPath + '/' + filename)
    return mySend(res, 0, '删除成功')

})

router.post('/update', async (req, res) => {
    const { filename, newFilename, token } = req.body
    const checked = checkParams({ filename, newFilename, token })
    if (checked) return mySend(res, 1, checked)
    const user = await Vtoken(token)
    if (!user) return mySend(res, 314, 'token不存在或已过期')

    let myPath = public + '/' + user.username;
    fs.renameSync(myPath + '/' + filename, myPath + '/' + newFilename)
    return mySend(res, 0, 'ok')

})

router.post('/list', async (req, res) => {
    const { token, size = 10, current = 1 } = req.body
    const user = await Vtoken(token)
    if (!user) return mySend(res, 314, 'token不存在或已过期')

    let [err, total] = await to(File.countDocuments({userId: user._id}))
    if(err) return mySend(res, 1, '查询失败', err)
    let [err1, result] = await to(File.find({userId: user._id}).sort({ctime: -1}).skip((current - 1) * size).limit(size))
    if(err1) return mySend(res, 1, '查询失败', err1)
    console.log(result)
    
    return mySend(res, 0, 'success', {current: 1,
        fileList: [],
        size: 12,
        total: 0,})

})

const mkdirPath = pathStr => {
    console.log(pathStr)
    var projectPath=path.join(process.cwd());
    console.log(process.cwd())
    var tempDirArray=pathStr.split('\\');
    // console.log(tempDirArray)

    for (var i = 0; i < tempDirArray.length; i++) {
        projectPath = projectPath+'/'+tempDirArray[i];
        if (fs.existsSync(projectPath)) {
            var tempstats = fs.statSync(projectPath);
            if (!(tempstats.isDirectory())) {
                fs.unlinkSync(projectPath);
                fs.mkdirSync(projectPath);
            }
        }
        else{
            fs.mkdirSync(projectPath);
        }
    }
    console.log(projectPath)
    return projectPath;
}

module.exports = router